package com.dm.server.xxl_job;

import com.dm.server.entity.BlogLike;
import com.dm.server.mapper.BlogLikeMapper;
import com.dm.server.mapper.BlogMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Set;

@Component
public class LikeSyncJob {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BlogLikeMapper blogLikeMapper;
    // MyBatis-Plus Mapper

    @Autowired
    private BlogMapper blogMapper;
    //博客表Mapper

    @XxlJob("likeSyncJobHandler")
    public void likeSyncJobHandler() {
        // 1. 获取所有博客ID（假设你有办法获取所有blogId列表）
        Set<String> blogIdKeys = redisTemplate.keys("blog:like:*");
        if (blogIdKeys == null || blogIdKeys.isEmpty()) {
            return;
        }

        for (String key : blogIdKeys) {
            // 2. 解析blogId
            String blogIdStr = key.substring("blog:like:".length());
            Long blogId = Long.valueOf(blogIdStr);

            // 3. 获取该博客所有点赞用户ID
            Set<String> userIdSet = redisTemplate.opsForSet().members(key);
            if (userIdSet == null || userIdSet.isEmpty()) {
                continue;
            }

            int successCount = 0;
            for (String userIdStr : userIdSet) {
                Long userId = Long.valueOf(userIdStr);
                BlogLike like = new BlogLike();
                like.setUserId(userId);
                like.setBlogId(blogId);
                try {
                    blogLikeMapper.insert(like); // 利用唯一索引防止重复
                    successCount++;
                } catch (Exception e) {
                    // 可能是唯一索引冲突，已存在则跳过
                }
            }

            // 4. 点赞数累加
            if (successCount > 0) {
                blogMapper.incrementLikeCount(blogId, successCount);
            }

            // 5. 清理Redis
            redisTemplate.delete(key);
        }
    }
}